package cn.rongdao.jrkabao.widget;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;

import com.mifengkong.frtools.util.FRDisplayMetrics;
import com.mifengkong.frtools.util.FRString;

import java.util.ArrayList;
import java.util.List;

import cn.rongdao.jrkabao.R;

/**
 * Created by jack on 2017/7/28
 */

public class CustomPieChart extends View {

    private float outSideRadius;
    private float inSideRadius;
    private Paint mPaint;
    private int[] colors = {Color.parseColor("#ff712d"), Color.parseColor("#ffc534")};

    private List<String> moneyList = new ArrayList<>();
    private float totalMoney;
    private RectF rectF;

    private boolean isHaveData;

    private ValueAnimator animator;

    private float offset = 0;

    private boolean isStart;

    public CustomPieChart(Context context) {
        this(context, null);
    }

    public CustomPieChart(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomPieChart(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray array = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomPieChart, defStyleAttr, 0);
        outSideRadius = array.getDimension(R.styleable.CustomPieChart_outside_radius, FRDisplayMetrics.dp2px(getContext(), 61.0f));
        inSideRadius = array.getDimension(R.styleable.CustomPieChart_inside_radius, FRDisplayMetrics.dp2px(getContext(), 25.0f));

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(outSideRadius - inSideRadius);
        initAnimator();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        int centerX = getWidth() / 2;
        int centerY = getHeight() / 2;
        float radius = outSideRadius - inSideRadius;
        rectF = new RectF(centerX - radius, centerY - radius, centerX + radius, centerY + radius);
    }

    public void setMoneyList(List<String> moneyList, boolean isHaveData) {
        this.moneyList.clear();
        this.moneyList.addAll(moneyList);
        this.isHaveData = isHaveData;
        totalMoney = 0;
        for (String s : this.moneyList) {
            if (!FRString.isEmpty(s)) {
                totalMoney += Float.valueOf(s);
            }
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (!isHaveData) {
            mPaint.setColor(ContextCompat.getColor(getContext(), R.color.colorPrimary));
            canvas.drawArc(rectF, 0, offset, false, mPaint);
        } else if (null != moneyList && moneyList.size() > 0) {
            float currentAngle = 0.0f;
            for (int i = 0; i < moneyList.size(); i++) {
                if (i >= colors.length) {
                    break;
                }
                if (!FRString.isEmpty(moneyList.get(i)) && Float.valueOf(moneyList.get(i)) > 0) {
                    float needDrawAngle = Float.valueOf(moneyList.get(i)) * 1.0f / totalMoney * 360;
                    if (Math.min(needDrawAngle, offset - currentAngle) >= 0) {
                        mPaint.setColor(colors[i]);
                        canvas.drawArc(rectF, currentAngle, Math.min(needDrawAngle, offset - currentAngle), false, mPaint);
                    }
                    currentAngle += needDrawAngle;
                }
            }
        }
    }

    private void initAnimator() {
        animator = ValueAnimator.ofFloat(0, 360);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                offset = (float) animation.getAnimatedValue();
                postInvalidate();
            }
        });
        animator.setDuration(1000);
        animator.setInterpolator(new LinearInterpolator());
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                isStart = true;
            }

            @Override
            public void onAnimationEnd(Animator animation) {

            }

            @Override
            public void onAnimationCancel(Animator animation) {
                isStart = false;
            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }

    public void startAnim() {
        if (null != animator && !isStart) {
            animator.start();
        }
    }

    public void stopAnim() {
        if (null != animator) {
            animator.cancel();
            animator = null;
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width;
        int height;
        int mode = MeasureSpec.getMode(widthMeasureSpec);
        int size = MeasureSpec.getSize(widthMeasureSpec);

        if (mode == MeasureSpec.EXACTLY) {
            width = size;
        } else {
            width = (int) (2 * outSideRadius + getPaddingLeft() + getPaddingRight());
        }

        mode = MeasureSpec.getMode(heightMeasureSpec);
        size = MeasureSpec.getSize(heightMeasureSpec);
        if (mode == MeasureSpec.EXACTLY) {
            height = size;
        } else {
            height = (int) (2 * outSideRadius + getPaddingTop() + getPaddingBottom());
        }
        setMeasuredDimension(width, height);
    }
}
